<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card class="filter-container" shadow="never">
      <div class="filter-item">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入分类名称"
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
        <el-button type="primary" @click="handleQuery">查询</el-button>
        <el-button @click="resetQuery">重置</el-button>
        <el-button type="primary" @click="handleAdd">新增</el-button>
      </div>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="table-container">
      <el-table
        v-loading="loading"
        :data="categoryList"
        style="width: 100%"
        border
      >
        <el-table-column prop="categoryId" label="ID" width="80" />
        <el-table-column prop="categoryName" label="分类名称" />
        <el-table-column prop="imageUrl" label="分类图片">
          <template #default="scope">
            <el-image 
              style="width: 80px; height: 80px"
              :src="scope.row.imageUrl"
              :preview-src-list="[scope.row.imageUrl]">
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="isHot" label="是否热门">
          <template #default="scope">
            <el-tag :type="scope.row.isHot === 1 ? 'success' : 'info'">
              {{ scope.row.isHot === 1 ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag :type="scope.row.status === 0 ? 'success' : 'info'">
              {{ scope.row.status === 0 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template #default="scope">
            <el-button
              size="small"
              type="primary"
              link
              @click="handleUpdate(scope.row)"
            >编辑</el-button>
            <el-button
              size="small"
              type="danger"
              link
              @click="handleDelete(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分类编辑对话框 -->
    <el-dialog 
      :title="dialogTitle" 
      v-model="dialogVisible" 
      width="500px"
      :close-on-click-modal="false"
      @close="handleClose"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="分类图片" prop="imageUrl">
          <el-upload
            class="avatar-uploader"
            :action="action"
            :show-file-list="false"
            :headers="{ Authorization: 'Bearer ' + getTk() }"
            :on-success="handleImageSuccess"
            :before-upload="beforeImageUpload">
            <img v-if="form.imageUrl" :src="form.imageUrl" class="avatar">
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="是否热门" prop="isHot">
          <el-switch
            v-model="form.isHot"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="form.status"
            :active-value="0"
            :inactive-value="1"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { listCategory, getCategory, addCategory, updateCategory, delCategory } from "@/api/product"
import { getToken } from '@/utils/auth'

interface CategoryForm {
  id?: number
  name: string
  imageUrl: string
  isHot: number
  status: number
}

interface QueryParams {
  name?: string
}

// 遮罩层
const loading = ref(false)
// 选中数组
const ids = ref<number[]>([])
// 弹出层标题
const dialogTitle = ref('')
// 是否显示弹出层
const dialogVisible = ref(false)
// 表单ref
const formRef = ref<FormInstance>()
// 分类列表
const categoryList = ref<any[]>([])
// const action = ref('http://localhost:8498/common/upload')
const action = ref('http://175.178.54.148:8498/common/upload')

// 查询参数
const queryParams = reactive<QueryParams>({
  name: undefined
})

// 表单参数
const form = reactive<CategoryForm>({
  id: undefined,
  name: '',
  imageUrl: '',
  isHot: 0,
  status: 0
})

// 表单校验
const rules = reactive<FormRules>({
  name: [
    { required: true, message: "分类名称不能为空", trigger: "blur" }
  ],
  imageUrl: [
    { required: true, message: "分类图片不能为空", trigger: "blur" }
  ]
})

/** 查询分类列表 */
const getList = async () => {
  loading.value = true
  try {
    const res = await listCategory(queryParams)
    categoryList.value = res.data
  } catch (error) {
    console.error('获取分类列表失败:', error)
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.name = undefined
  handleQuery()
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset()
  dialogTitle.value = "添加分类"
  dialogVisible.value = true
}

/** 修改按钮操作 */
const handleUpdate = async (row: any) => {
  reset()
  try {
    Object.assign(form, row)
    form.name = row.categoryName
    form.id = row.categoryId
    dialogTitle.value = "修改分类"
    dialogVisible.value = true
  } catch (error) {
    console.error('获取分类详情失败:', error)
  }
}

/** 提交按钮 */
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        console.log(form, 'fff')
        if (form.id) {
          await updateCategory(form)
          ElMessage.success("修改成功")
        } else {
          await addCategory(form)
          ElMessage.success("新增成功")
        }
        dialogVisible.value = false
        getList()
      } catch (error) {
        console.error('提交失败:', error)
      }
    }
  })
}

/** 删除按钮操作 */
const handleDelete = (row: any) => {
  ElMessageBox.confirm(
    '是否确认删除分类编号为"' + row.categoryId + '"的数据项?',
    "警告",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  ).then(async () => {
    try {
      await delCategory(row.categoryId)
      getList()
      ElMessage.success("删除成功")
    } catch (error) {
      console.error('删除失败:', error)
    }
  })
}

/** 表单重置 */
const reset = () => {
  form.id = undefined
  form.name = ''
  form.imageUrl = ''
  form.isHot = 0
  form.status = 0
  
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 图片上传成功处理
const handleImageSuccess = (res: any) => {
  form.imageUrl = res.url
}

// 上传图片前处理
const beforeImageUpload = (file: File) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('上传图片只能是 JPG/PNG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB!')
  }
  return isJPG && isLt2M
}

const handleClose = () => {
  reset()
  dialogVisible.value = false
}

const getTk = () => {
  return getToken()
}

onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.filter-container {
  margin-bottom: 20px;
}

.filter-item {
  display: inline-block;
  vertical-align: middle;
  margin-bottom: 10px;
}

.avatar-uploader {
  :deep(.el-upload) {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);

    &:hover {
      border-color: var(--el-color-primary);
    }
  }
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
}

.dialog-footer {
  padding-top: 20px;
  text-align: right;
  
  .el-button {
    margin-left: 10px;
  }
}
</style> 